import PromptPopup from '@/components/PromptPopup/PromptPopup.vue';
import api from '../../http/api.js';
import util from '../../http/util.js';
export default {
	components: {
		PromptPopup
	},
	data() {
		return {
			formData: {
				accountNumber: '',
				password: ''
			},

			errors: {
				accountNumber: '',
				password: ''
			},
			showPassword: false // 密码隐藏与可见
		}
	},
	onShow() {
		uni.$on('refreshData', (data) => {
			console.log('接收到的数据:', data);
			// 更新页面数据
			this.formData.accountNumber = data.key;
		});
	},
	methods: {
		// 验证账号
		validateAccountNumber() {
			const accountNumber = this.formData.accountNumber;
			if (!accountNumber) {
				this.errors.accountNumber = '账号/手机号不能为空';
			} else if (accountNumber.length < 6 || !/[a-zA-Z]/.test(accountNumber) || !/[0-9]/.test(accountNumber)) {
				this.errors.accountNumber = '请填写正确账号格式';
			} else {
				this.errors.accountNumber = '';
			}
		},
		// 验证密码
		validatePassword() {
			const password = this.formData.password;
			this.errors.password = '';
			if (!password) {
				this.errors.password = '密码不能为空';
				return;
			}
			if (password.length < 6) {
				this.errors.password = '密码长度至少6位';
				return;
			}
		},
		//确认弹窗退出登录
		collectMoney() {
			this.$refs.pointOut.closeModal();
		},
		//拉起弹窗
		getPopup() {
			this.$refs.pointOut.open();
		},
		//跳转注册
		getregister() {
			uni.navigateTo({
				url: '/pages/Login/register/index'
			})
		},
		//登录
		login() {
			this.validateAccountNumber();
			this.validatePassword();
			if (this.isFormValid) {
				uni.showLoading({
					title: '登录中...',
					mask: true
				});
				api.getLogin({
					"username": this.formData.accountNumber,
					"password": this.formData.password,
				}).then(res => {
					if (res.code == 1) {
						// 保存 token 和用户信息
						util.save({
							accessToken: res.data.userinfo.token,
							expiresIn: res.data.userinfo.expires_in,
							userInfo: res.data.userinfo
						});
						uni.switchTab({
							url: '/pages/Home/index'
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					this.handleRegisterError(err)
				}).finally(fer => {
					uni.hideLoading();
				})

			} else {
				uni.showToast({
					title: '密码或账号错误',
					icon: 'none',
					duration: 3000
				});
			}
		},
		// 错误处理
		handleRegisterError(error) {
			// 特定错误码处理
			if (error.code === 'PHONE_EXIST') {
				return uni.showToast({
					title: '帐号不存在',
					icon: 'none'
				});
			}
		
			// 网络错误处理
			if (error.code === 'NETWORK_ERROR') {
				return uni.showToast({
					title: '网络不稳定，请重试',
					icon: 'none'
				});
			}
		
			// 通用错误提示
			uni.showToast({
				title: error.msg || '登录失败，请重试',
				icon: 'none'
			});
		}
	},
	computed: {
		isFormValid() {
			return Object.values(this.errors).every(error => !error) &&
				Object.values(this.formData).every(val => val !== '');
		}
	},
}